<template>
  <Dialog
    v-model="dialogVisible"
    width="800px"
    :title="typeIndex === 'add' ? t('staff.add') : t('staff.edit')"
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
    maxHeight="680px"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="110px">
      <el-form-item :label="t('advertisement.title')" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item :label="t('advertisement.image')" prop="image">
        <UploadFile
          class="w-100%"
          url="/common/uploadFile"
          drag
          :file-type="['png', 'jpg', 'jpeg', 'bmp', 'pdf', 'docx', 'doc', 'xlsx', 'xls']"
          :params="{ directory: 5 }"
          :limit="1"
          :fileListMap="picList"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadCallback"
          @handle-remove-file="handleRemoveFile"
          @handle-picture-card-preview="handlePictureCardPreview"
        />
      </el-form-item>

      <el-form-item :label="t('advertisement.link')" prop="link">
        <el-input v-model="form.link" />
      </el-form-item>
      <el-form-item :label="t('advertisement.position')" prop="position">
        <el-select v-model="form.position" :filterable="true" :clearable="true">
          <el-option
            v-for="item in positionList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('advertisement.sort')" prop="sort">
        <el-input v-model="form.sort" type="number" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)">{{ t('common.cancel') }} </el-button>
      <el-button type="primary" @click="submit(formRef)">{{ t('common.save') }} </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createImageViewer } from '@/components/ImageViewer'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import { editInfoApi, createDataApi, getEnumApi } from '@/api/advertisement'
const emit = defineEmits(['refresh'])
const { t } = useI18n()

const dialogVisible = ref<boolean>(false)
const typeIndex = ref<string>()
const positionList = ref<Array<Record<string, any>>>([])
const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  title: '',
  sort: 1,
  image: 0,
  link: '',
  position: ''
})
//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  positionList.value = resp.data.position
}
// 表单验证规则
const rules = ref<FormRules>({
  title: [
    {
      required: true,
      message: t('advertisement.titleRequired'),
      trigger: ['blur']
    }
  ],
  position: [
    {
      required: true,
      message: t('advertisement.positionRequired'),
      trigger: ['blur']
    }
  ],
  image: [
    {
      required: true,
      message: t('advertisement.imageRequired'),
      trigger: ['blur']
    }
  ],
  link: [
    {
      required: true,
      message: t('advertisement.linkRequired'),
      trigger: ['blur']
    }
  ]
})
const picList = ref<any[]>([])
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 实际项目中替换为API调用
        console.log('fileObj', fileObj.value, form.value)
        form.value.image = fileObj.value ? fileObj.value.id : ''

        const resp =
          typeIndex.value === 'add'
            ? await createDataApi(form.value)
            : await editInfoApi(form.value)

        // 模拟API响应
        // const resp = { code: 0 }
        if (resp && resp.code === 0) {
          ElMessage.success(
            typeIndex.value === 'add'
              ? t('advertisement.createSuccess')
              : t('advertisement.updateSuccess')
          )
          closeDialog(formEl)
          emit('refresh')
        }
      } catch (error) {
        console.error('广告信息提交失败', error)
      }
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    title: '',
    position: '',
    image: 0,
    sort: 1,
    link: ''
  }
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = (type: string, row?: Record<string, any>) => {
  typeIndex.value = type
  picList.value = []
  fileObj.value = []
  getDropDownBoxInfo()
  if (type === 'edit') {
    form.value = row!
    if (form.value.image) {
      picList.value = [
        {
          name: form.value.imageName,
          id: form.value.imageId,
          url: form.value.image
        }
      ]
      fileObj.value = {
        name: form.value.imageName,
        id: form.value.imageId,
        url: form.value.image
      }
    }
  }
  if (form.value.support_currency) {
    form.value.support_currency = form.value.support_currency.split(',')
  }
}

defineExpose({
  dialogVisible,
  getBackShow
})
//上传成功以后回调
const fileObj = ref<any>(null)
const handleUploadCallback = (val: any) => {
  console.log('val', val)
  fileObj.value = val
}

const handleRemoveFile = (val: any) => {
  fileObj.value = null
}

const handlePictureCardPreview = (url: any) => {
  try {
    if (!url) return
    if (/\.(jpg|jpeg|png|gif|bmp)$/i.test(url))
      return createImageViewer({
        urlList: [url]
      })
    window.open(url)
  } catch (error) {
    console.error('预览图片失败:', error)
  }
}
</script>
<style lang="less" scoped>
.m-r-4 {
  margin-right: 16px;
}
</style>
